package com.corpgovernment.common.utils;


import com.alibaba.fastjson.JSONObject;
import com.ctrip.corp.obt.generic.utils.StringUtils;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: majl
 * @DateTime: 2019-5-20
 * @FileName: StringUtil
 * @Description
 */
@Deprecated
public class StringUtil {

    /**
     * 分隔字符串
     */
    public static final String SPLITSTRING = "♀";

    public static boolean isBlank(String str) {
        return (str == null || "".equals(str)) ? true : false;
    }

    public static boolean isInteger(String str) {
        try {
            Integer.parseInt(str);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    public static boolean isLong(String str) {
        try {
            Long.parseLong(str);
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    /**
     * 分转换成元
     *
     * @param cent
     * @return
     */
    public static String centToMoney(Long cent) {
        if (cent == null) {
            return "0";
        }
        return new BigDecimal(cent).divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP).stripTrailingZeros().toPlainString();
    }

    /**
     * 分转换成元
     *
     * @param cent
     * @return
     */
    public static String centToMoney(BigDecimal cent) {
        if (cent == null) {
            return "0";
        }
        return cent.divide(new BigDecimal(100), 2, BigDecimal.ROUND_UP).stripTrailingZeros().toPlainString();
    }

    /**
     * 金额处理
     *
     * @param cent
     * @return
     */
    public static String centToMoney(String cent) {
        if (isBlank(cent)) {
            return "0";
        }
        return new BigDecimal(cent).setScale(2, BigDecimal.ROUND_UP).stripTrailingZeros().toPlainString();
    }

    public static BigDecimal getBigDecimal(String cent) {
        if (isBlank(cent)) {
            return new BigDecimal(0);
        }
        return new BigDecimal(cent).setScale(2, BigDecimal.ROUND_UP);
    }

    /**
     * 对列表的类型中的某个字段进行拼接字符串
     * 目前支持：包装器类型、BigDecimal的转换、枚举类型
     *
     * @param objects   对象列表
     * @param clazz     列表类型的class
     * @param fieldName 需要拼接的字段名称
     * @param separator 分隔符
     * @param format    格式字符串，其中字段的值用"[fieldName]"标识，例如"%s [name] %s"；假如是BigDecimal的，则传入DecimalFormat的格式字符串。
     * @param params    格式化的值
     */
    public static <T> String appendString(List<T> objects, Class<T> clazz, String fieldName, String separator, String format, Object... params) throws NoSuchFieldException, IllegalAccessException {
        StringBuilder text = new StringBuilder();
        if (objects == null || objects.size() <= 0) {
            return text.toString();
        }
        Field[] fields = clazz.getDeclaredFields();
        Field currentField = null;
        for (Field field : fields) {
            if (field.getName().equals(fieldName)) {
                currentField = field;
                currentField.setAccessible(true);
            }
        }
        if (currentField == null) {
            throw new NoSuchFieldException();
        }
        for (T object : objects) {
            String temp;
            String typeName = currentField.getType().getSimpleName();
            if ("char[]".equals(typeName)) {
                temp = String.valueOf((char[]) currentField.get(object));
            } else {
                temp = String.valueOf(currentField.get(object));
            }
            if (StringUtils.isNotBlank(format)) {
                format = format.replace("[" + fieldName + "]", temp);
                temp = String.format(format, params);
            }
            text.append(temp);
            text.append(separator);
        }
        if (objects.size() > 0) {
            text.deleteCharAt(text.length() - 1);
        }
        return text.toString();
    }

    /**
     * 转换string为int
     *
     * @param Str
     * @return
     */
    public static int convertStringToInt(String Str) {
        try {
            return Integer.parseInt(Str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 转换string为long
     *
     * @param Str
     * @return
     */
    public static long convertStringToLong(String Str) {
        try {
            return Long.parseLong(Str);
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 字符串是否存在字符串列表中
     *
     * @param source
     * @param params
     * @return
     */
    public static boolean In(String source, String... params) {
        if (params == null || params.length <= 0) {
            return false;
        }
        for (String s : params) {
            if (StringUtils.equalsIgnoreCase(s, source)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 字符串是否存在字符串列表中
     *
     * @param source
     * @param params
     * @return
     */
    public static boolean In(String source, List<String> params) {
        if (params == null || params.size() <= 0) {
            return false;
        }
        for (String s : params) {
            if (StringUtils.equalsIgnoreCase(s, source)) {
                return true;
            }
        }
        return false;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        System.out.println(centToMoney(1000L));
    }

    /**
     * 字符串花样匹配
     *
     * @param source
     * @param replaceJson
     * @param leftList
     * @param rightList
     * @return
     */
    public static String matchString(String source, JSONObject replaceJson, List<String> leftList, List<String> rightList) {
        // 为空则返回
        if (org.apache.commons.lang3.StringUtils.isBlank(source)) {
            return source;
        }
        // 替换匹配
        if (replaceJson != null && replaceJson.containsKey(source)) {
            source = replaceJson.getString(source);
            return source;
        }

        // 去括号匹配
        if (source.contains("(")) {
            source = source.substring(0, source.indexOf("("));
        }
        if (source.contains("（")) {
            source = source.substring(0, source.indexOf("（"));
        }

        // 左右匹配
        if (rightList != null && rightList.size() > 0 && leftList != null && leftList.size() > 0) {
            for (String tempData : rightList) {
                if (source.endsWith(tempData)) {
                    source = source.substring(0, source.indexOf(tempData));
                    break;
                }
            }
            for (String tempData : leftList) {
                if (source.startsWith(tempData)) {
                    source = source.substring(source.indexOf(tempData) + tempData.length());
                    return source;
                }
            }
        }

        // 右匹配
        if (rightList != null && rightList.size() > 0) {
            for (String tempData : rightList) {
                if (source.endsWith(tempData)) {
                    source = source.substring(0, source.indexOf(tempData));
                    return source;
                }
            }
        }

        // 左匹配
        if (leftList != null && leftList.size() > 0) {
            for (String tempData : leftList) {
                if (source.startsWith(tempData)) {
                    source = source.substring(source.indexOf(tempData) + tempData.length());
                    return source;
                }
            }
        }
        return source;
    }

    /**
     * 优化性能
     */
    private static Pattern sqlPattern = Pattern.compile("\\b(and|exec|insert|select|drop|grant|alter|delete|update|count|chr|mid|master|truncate|char|declare|or)\\b|(\\*|;|\\+|'|%)");

    /**
     * sql校验关键字
     *
     * @param sWord
     * @return
     */
    public static Boolean checkSqlParam(String sWord) {
        Matcher matcher = sqlPattern.matcher(sWord);
        return matcher.find();
    }

    /**
     * 是否包含特殊字符
     *
     * @param s
     * @return
     */
    public static boolean containsXssEncode(String s) {
        //XSS静态过滤方法
        if (s == null || s.isEmpty()) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '>':
                case '<':
                case '\'':
                case '&':
                case '%':
                    return true;
                default:
                    break;
            }
        }
        return false;
    }

    /**
     * 组合key
     */
    public static String getKey (Object ... objects){
        StringBuilder builder = new StringBuilder();
        for (Object object : objects) {
            if (builder.length() > 0){
                builder.append("_");
            }
            builder.append(object);
        }
        return builder.toString();
    }

    public static boolean havingChinese(String str) {
        if (StringUtils.isNotBlank(str)) {
            Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
            Matcher m = p.matcher(str);
            return m.find();
        }
        return false;
    }
}
